<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2019/9/18  9:45
 */

namespace App\Http\Controllers\Api;

use AlibabaCloud\Client\AlibabaCloud;
use App\Http\Util\Lib\StoreForget;
use App\Models\StaffModel;
use App\Models\OrderModel;
use App\Models\OrderInfoModel;
//use App\Models\StaffModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;
use phpDocumentor\Reflection\DocBlock\Tags\Return_;

class StaffController extends Controller
{
    /**
     * 中间件
     */
    public function __construct(){
        $this -> middleware('login_check');
            //->except(['nearby_store']);
    }

    /**
     * 获取员工资料
     * @param Request $request
     * @param StaffModel $staffModel
     */
    public function staff_info(Request $request,StaffModel $staffModel){
        $staff = $staffModel
            ->where('id',auth('api') -> user() -> id)
            ->select(['id','account','staff_name','staff_head','car_license','total_mileage','car_status','created_at'])
            ->first();

        $staff->staff_head = getDomain().'/'.'upload/'.$staff->staff_head;

        $total_mileage = Db::table('today_mileage')
            ->where('staff_id',auth('api') -> user() -> id)
            ->whereDate('created_at',date('Y-m-d'))
            //->orderBy('created_at','desc')
            ->sum('total_new_mileage');
       // var_dump($total_mileage);die;

        if(empty($total_mileage)){
            $total_mileage =0;
        }

        $staff->today_mileage = $total_mileage;
        //var_dump($staff);die;

        return response() -> json([
            'error_code' => 0,
            'msg' => '操作成功',
            'data' => $staff
        ]);
    }

    /**
     * 我的订单
     */
    public function my_order(Request $request,OrderModel $orderModel){

        //$orderModel

        $order = $orderModel
            ->with('order_info')
            ->where('staff_id',auth('api') -> user() -> id)
            ->get();

        return response() -> json([
            'error_code' => 0,
            'msg' => '操作成功',
            'data' =>$order
        ]);

    }

    /**
     * 今日里程上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function mileage_img(Request $request){

        try{

            // 验证规则
            $rule = [
                'photo' => 'required',
                'addresss' => 'required',
                //'order_id'=> 'required|exists:order,id'
            ];

            // 验证信息
            $message = [
                'photo.required' => '图片文件不能为空',
                'addresss.required' => '地址不能为空',
            ];

            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $img = $request->file('photo');

            $address = $request->input('addresss');

            // 获取文件后缀名
            $suffix = $img->getClientOriginalExtension();

            // 定义保存的路径
            $avatarUrl = 'uploads/images/'. date('Ymd');

            // 验证文件夹是否存在
            if(!is_dir($avatarUrl)){
                // 不存在则创建
                mkdir($avatarUrl,0777,true);
            }

            // 获取图片名称
            $imagesName = md5(time()). '.' . $suffix;

            $old_avatarUrl = $avatarUrl.'/' . $imagesName;

            $new_imagesName = $avatarUrl.'/xg_' . $imagesName;

            $img = Image::make($request->file('photo'))->save($old_avatarUrl);

            //var_dump(getDomain().'/'.$old_avatarUrl);die;

            if(!is_file($old_avatarUrl)){
                return response() -> json([
                    'error_code' => 400,
                    'msg' => '上传文件保存失败'
                ]);
            }

            $img->text($address, 10, 10,function($font) {
                $font->file(base_path().'/public/css/simsun.ttf');
                $font->size(18);
                $font->color('#000000');
                $font->valign('top');
            });

            $img->text(date("Y-m-d h:i:sa"), 10, 30,function($font) {
                $font->file(base_path().'/public/css/simsun.ttf');
                $font->size(18);
                $font->color('#000000');
                //$font->align('center');
                $font->valign('top');
                //$font->angle(45);
            });

            unlink($old_avatarUrl);

            $img->save($new_imagesName);

            //var_dump(dir_exist_file(getDomain().'/'.$new_imagesName));die;
            if(!is_file($new_imagesName)){
                return response() -> json([
                    'error_code' => 400,
                    'msg' => '修改文件保存失败'
                ]);
            }

            $mid = Db::table('images')->insertGetId(['url'=>$new_imagesName]);
            if(empty($mid)){
                return response() -> json([
                    'error_code' => 400,
                    'msg' => '图片url更新失败'
                ]);
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '保存成功',
                'data'=>[
                    'mid'=>$mid
                ]
            ]);


        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }

    /**
     * 发车
     */
    public function start_car(Request $request){
        //var_dump(date('Y-m-d'));die;
        try{

            // 验证规则
            $rule = [
                'start_mid' => 'required',
                'start_mileage' => 'required',
                'start_address' => 'required',
                //'order_id'=> 'required|exists:order,id'
            ];

            // 验证信息
            $message = [
                'start_mid.required' => '发车图片ID不能为空',
                'start_mileage.required' => '发车里程不能为空',
                'start_address.required' => '发车地址不能为空',
            ];

            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            //检查是否已发车
          /*  $st_mileage = Db::table('today_mileage')
                ->where('staff_id',auth('api') -> user() -> id)
                ->whereDate('created_at',date('Y-m-d'))
                ->first();*/

            //var_dump( auth('api') -> user() -> staff_name);die;

           $car_status =  auth('api') -> user() ->car_status;
          if($car_status==1){
              throw new \Exception('请先交车再进行发车');
          }
          date_default_timezone_set("PRC");
          //var_dump(date("Y-m-d h:i:s"));die;

            $res = Db::table('today_mileage')
                ->insert([
                    'staff_id'=>auth('api') -> user() -> id,
                    'start_mid'=>$request->input('start_mid'),
                    'start_mileage'=>$request->input('start_mileage'),
                    'start_address'=>$request->input('start_address'),
                    'created_at'=>date("Y-m-d H:i:s")]);

            if(!$res){
                throw new \Exception('发车记录提交失败');
            }

            //更新发车状态
            Db::table('staff')
                ->where('id',auth('api') -> user() -> id)
                ->update(['car_status'=>1]);

            return response() -> json([
                'error_code' => 0,
                'msg' => '提交成功'
            ]);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }


    /**
     * 交车
     */
    public function end_car(Request $request,StaffModel $staffModel){

        try{
            // 验证规则
            $rule = [
                'deliver_mid' => 'required',
                'deliver_mileage' => 'required',
                'end_address' => 'required'

                //'order_id'=> 'required|exists:order,id'
            ];
           // <a href="<{$doc.document}>" download="<{$doc.document_name}>">点击下载</a>
            // 验证信息
            $message = [
                'deliver_mid.required' => '交车图片ID不能为空',
                'deliver_mileage.required' => '交车里程不能为空',
                'end_address.required' => '交车地址不能为空'
            ];

            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            //$request->input('mileage_id');

            //检查是否已发车
            $st_mileage = Db::table('today_mileage')
                ->where('staff_id',auth('api') -> user() -> id)
                ->whereDate('created_at',date('Y-m-d'))
                ->orderBy('created_at','desc')
                ->first();
            //echo 111111;die;
            if(empty($st_mileage)&&auth('api') -> user()->car_status==1){
                //
                $st_mileage = Db::table('today_mileage')
                    ->where('staff_id',auth('api') -> user() -> id)
                    //->whereDate('created_at',date('Y-m-d'))
                    ->orderBy('created_at','desc')
                    ->first();
            }

            if(empty($st_mileage)){
                throw new \Exception('找不到发车记录');
            }

            //var_dump($st_mileage);die;


            $car_status =  auth('api') -> user() ->car_status;
            if($car_status!=1&&empty($st_mileage)){
                throw new \Exception('请先发车再进行交车');
            }


            if($request->input('deliver_mileage')<$st_mileage->start_mileage){
                throw new \Exception('交车里程不能小于发车里程');
            }

            //计算今日里程
            $mileage = $request->input('deliver_mileage')-$st_mileage->start_mileage;

            date_default_timezone_set("PRC");
            $res = Db::table('today_mileage')
                ->where('staff_id',auth('api') -> user() -> id)
                ->where('id',$st_mileage->id)
                ->update([
                    'deliver_mid'=>$request->input('deliver_mid'),
                    'deliver_mileage'=>$request->input('deliver_mileage'),
                    'end_address'=>$request->input('end_address'),
                    'total_new_mileage'=>$mileage,
                    'updated_at'=>date('Y-m-d H:i:s')
                    ]);

            if(!$res){
                throw new \Exception('交车记录提交失败');
            }


            $st_today_mileage = Db::table('staff')
                ->where('id',$st_mileage->staff_id)
                ->update(['today_mileage'=>$mileage,'car_status'=>2,'updated_at'=>date("Y-m-d H:i:s")]);

            $up_total_mileage = Db::table('staff')
                ->where('id',$st_mileage->staff_id)
                ->increment('total_mileage', $mileage);

            if(!$st_today_mileage||!$up_total_mileage){
                throw new \Exception('里程记录更新失败');
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '提交成功'
            ]);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }


    /**
     * 更改个人信息
     * @param Request $request
     * @param MemberModel $memberModel
     * @return \Illuminate\Http\JsonResponse
     */
    public function editStaff(Request $request,StaffModel $staffModel){
        try {
            // 验证规则
            $rule = [
                'staff_name' => 'required',
                'car_license' => 'required',
                //'sex' => 'required'
            ];

            // 验证信息
            $message = [
                'staff_name.required' => '用户名不能为空',
                'car_license.required' => '车牌不能为空',
                //'phone.required' => '手机号码不能为空',
                //'sex.required' => '性别不能为空'
            ];

            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            date_default_timezone_set("PRC");
            $member = auth('api') -> user();

            //$member ->username = $request->input('username');
           // $member ->phone = $request->input('phone');
            $member ->staff_name = $request->input('staff_name');
            $member ->car_license = $request->input('car_license');
            //$member ->password = $request->input('password');

            $res = $member->save();
            if(!$res){
                throw new \Exception('更新失败');
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '更新成功'
            ]);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }


    /**
     * 更改密码
     * @param Request $request
     * @param MemberModel $memberModel
     * @return \Illuminate\Http\JsonResponse
     */
    public function editPassword(Request $request,StaffModel $staffModel){
        try {
            // 验证规则
            $rule = [
                //'staff_name' => 'required',
                'password' => 'required',
                'old_password' => 'required',
                //'sex' => 'required'
            ];

            // 验证信息
            $message = [
               // 'staff_name.required' => '用户名不能为空',
                'password.required' => '密码不能为空',
                'old_password.required' => '原密码不能为空',
                //'phone.required' => '手机号码不能为空',
                //'sex.required' => '性别不能为空'
            ];

            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            date_default_timezone_set("PRC");
            $member = auth('api') -> user();

            if(!\Hash::check($request->input('old_password'), auth('api') -> user()->password)){
                throw new \Exception('原密码不正确');
            }

            //$member ->username = $request->input('username');
            // $member ->phone = $request->input('phone');
            //$member ->staff_name = $request->input('staff_name');
            $member ->password = $request->input('password');

            $res = $member->save();
            if(!$res){
                throw new \Exception('更新失败');
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '更新成功'
            ]);

        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }

    /**
     * 更换头像
     */
    public function edit_head(Request $request){
        try{

            // 验证规则
            $rule = [
                'photo' => 'required',

            ];

            // 验证信息
            $message = [
                'photo.required' => '图片文件不能为空',

            ];
            date_default_timezone_set("PRC");
            $validator = Validator::make($request->all(), $rule, $message);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }

            $img = $request->file('photo');


            // 获取文件后缀名
            $suffix = $img->getClientOriginalExtension();

            // 定义保存的路径
            $avatarUrl = 'images/'. date('Ymd');

            // 验证文件夹是否存在
            if(!is_dir('upload/'.$avatarUrl)){
                // 不存在则创建
                mkdir('upload/'.$avatarUrl,0777,true);
            }

            // 获取图片名称
            $imagesName = md5(time()). '.' . $suffix;

            $old_avatarUrl = $avatarUrl.'/' . $imagesName;

            $url = 'upload/'.$old_avatarUrl;

            $img = Image::make($request->file('photo'))->save($url);

            if(!is_file($url)){
                return response() -> json([
                    'error_code' => 400,
                    'msg' => '上传文件保存失败'
                ]);
            }


            //$mid = Db::table('images')->insertGetId(['url'=>$old_avatarUrl]);
            $member = auth('api') -> user();

            //$member ->username = $request->input('username');
            // $member ->phone = $request->input('phone');
            $member ->staff_head = $old_avatarUrl;

            $res = $member->save();

            if(!$res){
                return response() -> json([
                    'error_code' => 400,
                    'msg' => '图片url更新失败'
                ]);
            }

            return response() -> json([
                'error_code' => 0,
                'msg' => '保存成功'
            ]);


        }catch (\Exception $e){
            return response() -> json([
                'error_code' => 400,
                'msg' => $e -> getMessage()
            ]);
        }

    }



}
